package com.loubobooo.personal.blog.controller;

import com.google.common.collect.Maps;
import com.loubobooo.personal.blog.common.ServerResponse;
import com.loubobooo.personal.blog.service.FileService;
import com.loubobooo.personal.blog.util.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@Slf4j
public class UploadController {

    @Resource
    private FileService fileService;

    // 普通上传文件
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file){

        Map<String,Object> resultMap = Maps.newHashMap();

        String path = request.getSession().getServletContext().getRealPath("upload");
        log.info("================这是上传的路径:{}================",path);
        if(!file.isEmpty()) {
            try {
                String targetFileName = fileService.upload(file, path);
                String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;

                resultMap.put("src", url);//图片url
                resultMap.put("title", file.getOriginalFilename());//图片名称，这个会显示在输入框里

                return ServerResponse.createBySuccess("上传成功！", resultMap);
            }
            catch (Exception e) {
                log.error("上传文件失败,", e);
            }
        }
        return ServerResponse.createByErrorMessage("上传失败！");
    }

    /**
      * @Description: ckeditor编辑器的上传图片
      * @return     返回类型
      * @date 2018/3/27 18:33
      */
    @RequestMapping(value = "/ckeditor-upload-image", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(HttpServletRequest request, @RequestParam("upload") MultipartFile file, @RequestParam(value = "CKEditorFuncNum") String funcNumber){

        Map<String,Object> resultMap = Maps.newHashMap();

        String path = request.getSession().getServletContext().getRealPath("upload");
        log.info("================这是上传的路径:{}================",path);
        if(!file.isEmpty()) {
            try {
                String targetFileName = fileService.upload(file, path);
                String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;

                String result = String.format("<script>window.parent.CKEDITOR.tools.callFunction(%s, '%s')</script>", funcNumber, url);
                return result;
            }
            catch (Exception e) {
                log.error("上传文件失败,", e);
            }
        }
        return null;
    }



/*    @RequestMapping(value = "/upload_index", method = RequestMethod.GET)
    public ModelAndView index() {
        return new ModelAndView("/admin/upload_index");
    }*/

/*    @RequestMapping(value = "/upload", method = RequestMethod.POST) //new annotation since 4.3
    public String singleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest,
            RedirectAttributes redirectAttributes) {
        String path = httpServletRequest.getSession().getServletContext().getRealPath("upload");
        try {
            String targetFileName = fileService.upload(file,path);
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
            redirectAttributes.addFlashAttribute("path",
                    "file path url '" + url + "'");
        } catch (Exception e) {
            log.error("upload file failed",e);
        }
        return "redirect:/uploadStatus";
    }*/

/*    @RequestMapping(value = "/uploadStatus", method = RequestMethod.GET)
    public String uploadStatus() {
        return "/admin/uploadStatus";
    }*/



    /**
      * @Description: fastDFS上传
      * @return     返回类型
      * @date 2018/3/20 14:19
      */
 /*   public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream=multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            log.error("upload file Exception!",e);
        }
        if (fileAbsolutePath==null) {
            log.error("upload file failed,please upload again!");
        }
        String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
        return path;
    }*/

}

